import 'dart:io';
import 'dart:math';
import 'package:path/path.dart' as path;

import 'package:uuid/uuid.dart';
import 'package:sainbainu/common/enums/platform_type.dart';
import 'package:sainbainu/common/values/constant.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

/// Util 工具类
class Util {
  ///
  /// Duration 转为 分钟:秒 格式
  ///
  static String toMMSS(Duration duration) {
    String twoDigits(int n) {
      if (n >= 10) return "$n";
      return "0$n";
    }

    String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
    String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
    return "$twoDigitMinutes:$twoDigitSeconds";
  }

  ///
  /// 生成随机字符串
  ///
  static String generateRandomString({int length = 10}) {
    final random = Random();
    const availableChars =
        'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890';
    final randomString = List.generate(length,
            (index) => availableChars[random.nextInt(availableChars.length)])
        .join();

    return randomString;
  }

  ///
  /// 字节数转兆字节
  ///
  static double bytesToMegabytes(int bytes) {
    return bytes / (1024 * 1024);
  }

  ///
  /// AssetEntity 转 File 对象
  ///
  static Future<List<File>> assetEntityToFiles(List<AssetEntity> assets) async {
    List<File> fileList = [];
    for (var ae in assets) {
      var file = await ae.file;
      if (file != null) {
        fileList.add(file);
      }
    }
    return fileList;
  }

  ///
  /// 过滤 AssetEntity 列表
  ///
  static Future<List<AssetEntity>> filterAssetsEntiteis(
    List<AssetEntity> assets, {
    double? maxSize,
    void Function(String msg)? onError,
  }) async {
    double noramlMaxSize = maxSize ?? AppConstant.imageMaxSize;

    // assets 转 files
    List<File> fileList = await Util.assetEntityToFiles(assets);
    List<AssetEntity> newAssets = [];

    for (var i = 0; i < fileList.length; i++) {
      var file = fileList[i];
      // 获取文件大小 并转为MB
      int fileBytes = await file.length();
      var fileSize = Util.bytesToMegabytes(fileBytes);
      // 判断是否超出限制
      if (fileSize > noramlMaxSize) {
        continue;
      }
      newAssets.add(assets[i]);
    }

    if (newAssets.length < assets.length && onError != null) {
      onError('${assets.length - newAssets.length}个文件大小超出${noramlMaxSize}M的限制');
    }

    return newAssets;
  }

  ///
  /// 手机号中间*代替
  ///
  static String obscurePhoneNumber(String phoneNumber) {
    // 判断手机号的长度
    int length = phoneNumber.length;

    // 长度小于等于4位，无法遮掩
    if (length <= 4) {
      return phoneNumber;
    }

    // 保留前3位和后4位，如果号码长度不足，则调整保留长度
    int frontLength = length >= 7 ? 3 : length ~/ 2;
    int endLength = length >= 7 ? 4 : length - frontLength;

    String start = phoneNumber.substring(0, frontLength);
    String end = phoneNumber.substring(length - endLength);

    // 用*替换中间部分
    return "$start${'*' * (length - frontLength - endLength)}$end";
  }

  ///
  /// 获取当前平台类型
  ///
  static PlatformType getCurrentPlatformType() {
    PlatformType platformType;
    if (Platform.isIOS) {
      platformType = PlatformType.ios;
    } else if (Platform.isAndroid) {
      platformType = PlatformType.android;
    } else {
      platformType = PlatformType.all;
    }
    return platformType;
  }

  ///
  /// 对比版本号
  ///
  static bool chechVersionCode(int localVersionCode, int? serviceVersionCode) {
    if (serviceVersionCode != null && serviceVersionCode > localVersionCode) {
      return true;
    }
    return false;
  }

  ///
  /// 获取路径中的文件名
  ///
  static String getFileName(String filePath) {
    return path.basename(filePath);
  }

  ///
  /// 生成唯一文件名
  ///
  static String generateUniqueFileName(String fileName) {
    // 生成唯一ID
    var uuid = const Uuid().v4();
    // 获取文件扩展名
    String extension = path.extension(fileName);
    // 拼接唯一文件名
    return '$uuid$extension';
  }

  ///
  /// 获取 URL 中的参数
  ///
  static Map<String, String> getUrlParams(String url) {
    Uri uri = Uri.parse(url);
    return uri.queryParameters;
  }
}
